package org.diysearch.services;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.diysearch.helpers.MailHelper;
import org.diysearch.helpers.PageHelper;
import org.diysearch.helpers.UserHelper;
import org.diysearch.interfaces.Product;
import org.diysearch.models.Page;
import org.diysearch.models.Status;
import org.diysearch.products.JsonProduct;
import org.diysearch.tools.BaseTool;
import org.diysearch.tools.StringTools;

public class Register extends BaseService {
	private static final Log LOG = LogFactory.getLog(Register.class);
	private String uri;

	@Override
	public Product execute() throws Exception {

		Product p = new JsonProduct();
		p.setWriter(writer);

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		int permissions = BaseTool.CONFIG_BEAN.getDefaultUserPermissions();
		int rating = 0;
		String auth = BaseTool.CONFIG_BEAN.getDefaultAuth();
		int status = 0; // we default status to 0, meaning we are awaiting
						// confirmation
		int uid = 0;
		int authType = 0;
		Status s = new Status();
		try {
			int code = UserHelper.save(uid, username, password, email,
					permissions, status, authType, auth, rating, null);
			
			// get the template to handle the email
			Page page = PageHelper.getPage(uri);
			Map<String,Object> content = new HashMap<String,Object>();
			content.put("page", page);
			content.put("token", StringTools.getMD5(username + email));
			String body = template.getContent(page.getTemplate(), content).toString();
			
			MailHelper.send(email, BaseTool.CONFIG_BEAN.getDoNotReplyAddr(),
					BaseTool.CONFIG_BEAN.getEmailSubject()
							+ " Confirm Registration", body);
			s.setCode(code);
			s.setMessage("new user created");
			s.addAttribute("email", email);
		} catch (Exception ex) {
			s.setCode(-1);
			s.setMessage("an error occured trying to create user");
			LOG.error(StringTools.getStackTrace(ex));
		}
		p.setOutput(s);
		return p;
	}

	@Override
	public boolean isWriter() {
		return true;
	}

	@Override
	public String getUri() {
		return uri;
	}

	@Override
	public void setUri(String uri) {
		this.uri = uri;
	}

}
